<template>
    <div class="wh-100% flex flex-col gap-2.5">
        <n-card>
            <n-form label-placement="left" :show-feedback="false">
                <n-grid :cols="4" :x-gap="30">
                    <n-form-item-gi label="用户id">
                        <n-input v-model:value="searchContent.userId"></n-input>
                    </n-form-item-gi>
                    <n-form-item-gi label="错误标题">
                        <n-input v-model:value="searchContent.title"></n-input>
                    </n-form-item-gi>
                    <n-form-item-gi label="提交时间">
                        <n-date-picker
                            v-model:value="daterange"
                            type="daterange"
                            clearable
                        />
                    </n-form-item-gi>
                </n-grid>
            </n-form>
            <div class="w-full flex justify-end gap-10px">
                <n-button :focusable="false" @click="handleResetContent">
                    <template #icon>
                        <n-icon :component="Reload" />
                    </template>
                    重置
                </n-button>
                <n-button :focusable="false" @click="handleSearchProblem">
                    <template #icon>
                        <n-icon :component="Search" />
                    </template>
                    查找
                </n-button>
            </div>
        </n-card>
        <n-card class="flex-1" content-class="flex">
            <template #header>
                <div class="w-full flex justify-between">
                    <div class="font-size-4">问题列表</div>
                    <div class="flex gap-2.5">
                        <n-button :focusable="false" @click="handleReset">
                            <template #icon>
                                <n-icon :component="Reload" />
                            </template>
                            刷新
                        </n-button>
                        <n-tabs
                            v-model:value="currentStatus"
                            type="segment"
                            size="small"
                            class="w-160px"
                            @update:value="handleChangeStatus"
                        >
                            <n-tab :name="0">未处理</n-tab>
                            <n-tab :name="1">已处理</n-tab>
                        </n-tabs>
                    </div>
                </div>
            </template>
            <div v-if="currentProblems.length === 0" class="flex-1 flex-center">
                <n-result status="404" title="暂无数据"> </n-result>
            </div>
            <n-data-table
                v-else
                :columns="
                    problemColumns(
                        handleResponseProblem,
                        handleDeleteProblem,
                        currentStatus
                    )
                "
                :data="currentProblems"
                :border="false"
                :scroll-x="currentStatus === 0 ? 0 : 1800"
            />
            <template #footer>
                <div class="w-full flex justify-between">
                    <span>共 {{ pagination[currentStatus].total }} 条</span>
                    <n-pagination
                        v-model:page="pagination[currentStatus].page"
                        :page-count="
                            Math.ceil(
                                pagination[currentStatus].total /
                                    pagination[currentStatus].size
                            )
                        "
                        :page-size="pagination[currentStatus].size"
                        @update:page="handleChangePage"
                    />
                </div>
            </template>
        </n-card>
        <n-drawer
            v-model:show="drawerShow"
            :auto-focus="false"
            position="right"
            width="400"
        >
            <n-drawer-content>
                <template #header>问题答复</template>
                <n-form class="select-none">
                    <n-form-item label="用户id">
                        <n-input
                            v-model:value="currentProblem.customerId"
                            disabled
                        />
                    </n-form-item>
                    <n-form-item label="问题标题">
                        <n-input
                            v-model:value="currentProblem.title"
                            disabled
                        />
                    </n-form-item>
                    <n-form-item label="问题内容">
                        <n-input
                            v-model:value="currentProblem.description"
                            type="textarea"
                            disabled
                        />
                    </n-form-item>
                    <n-form-item label="答复内容">
                        <n-input
                            v-model:value="response"
                            type="textarea"
                            maxlength="100"
                            show-count
                            clearable
                        />
                    </n-form-item>
                </n-form>
                <template #footer>
                    <n-button
                        class="w-25"
                        type="primary"
                        :focusable="false"
                        @click="confirmResponse"
                    >
                        确认
                    </n-button>
                </template>
            </n-drawer-content>
        </n-drawer>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, watch, onMounted } from "vue";
import { Search, Reload, Trash } from "@vicons/ionicons5";

import { Problem } from "@/types/problem";
import { ProblemSearchDto } from "@/service/api/dto/problem.dto";
import {
    getTreatedProblemList,
    getUntreatedProblemList,
    responseProblem,
    deleteProblem,
} from "@/service/api/problem";

import { problemColumns } from "@/utils/table-column";

// 查找问题表单
const emptySearchContent: ProblemSearchDto = {
    userId: null,
    title: null,
    startDate: null,
    endDate: null,
};
// 查找问题表单
const searchContent = reactive<ProblemSearchDto>(
    structuredClone(emptySearchContent)
);
// 查找日期
const daterange = ref<[number, number] | null>(null);
let searchConditions: Partial<ProblemSearchDto | null> = null;

// 分页
const pagination = reactive({
    0: {
        page: 1,
        size: 10,
        total: 0,
    },
    1: {
        page: 1,
        size: 10,
        total: 0,
    },
});

// 问题缓存
const problems = {
    0: new Map<number, Problem[]>([]),
    1: new Map<number, Problem[]>(),
};
// 当前问题页
const currentProblems = ref<Problem[]>([]);

const currentStatus = ref<0 | 1>(0);

// 当前操作的问题数据
const currentProblem = ref<Problem>({
    id: "",
    customerId: "",
    title: "",
    description: "",
    submitTime: 0,
    status: 0,
    response: "",
    responseTime: 0,
});

const drawerShow = ref(false);
// 答复内容
const response = ref("");

watch(daterange, (val) => {
    if (val) {
        searchContent.startDate = val[0];
        searchContent.endDate = val[1];
    } else {
        searchContent.startDate = null;
        searchContent.endDate = null;
    }
});

const handleGetProblems = async () => {
    try {
        const status = currentStatus.value;
        // 获取问题数据
        const res =
            status === 0
                ? await getUntreatedProblemList(
                      pagination[0].page,
                      pagination[0].size,
                      searchConditions ?? {}
                  )
                : await getTreatedProblemList(
                      pagination[1].page,
                      pagination[1].size,
                      searchConditions ?? {}
                  );
        // 设置总条数
        pagination[status].total = res.count;
        // 缓存当前页数据
        problems[status].set(pagination[status].page, res.problems);
        // 设置当前页数据
        currentProblems.value = res.problems;
    } catch (err) {
        console.log(err);
        window.NMessage.error((err as Error).message);
    }
};

onMounted(async () => {
    await handleGetProblems();
});

const handleReset = () => {
    pagination[0].page = 1;
    pagination[1].page = 1;
    problems[0].clear();
    problems[1].clear();

    response.value = "";
    handleGetProblems();
};

const handleSearchProblem = async () => {
    if (JSON.stringify(emptySearchContent) === JSON.stringify(searchContent)) {
        window.NMessage.warning("请输入搜索条件");
        return;
    }
    searchConditions = Object.fromEntries(
        Object.entries(searchContent).filter(
            ([_, value]) => value !== null && value !== ""
        )
    );
    handleReset();
};

const handleResetContent = () => {
    Object.assign(searchContent, emptySearchContent);
    daterange.value = null;

    searchConditions = null;
    handleReset();
};

const handleResponseProblem = (problem: Problem) => {
    drawerShow.value = true;
    currentProblem.value = problem;

    if (currentStatus.value === 1) {
        response.value = problem.response;
    }
};

const confirmResponse = async () => {
    if (response.value.length === 0) {
        window.NMessage.warning("请输入答复");
        return;
    }
    if (response.value === currentProblem.value.response) {
        window.NMessage.warning("请修改答复内容");
        return;
    }
    window.NDialog.info({
        title: "确认答复",
        content: "确认答复？",
        closable: false,
        positiveText: "确认",
        negativeText: "取消",
        onPositiveClick: async () => {
            try {
                await responseProblem(currentProblem.value.id, response.value);
                window.NMessage.success("答复成功");
                drawerShow.value = false;
                handleReset();
            } catch (err) {
                window.NMessage.error((err as Error).message);
            }
        },
    });
};

const handleDeleteProblem = (row: Problem) => {
    window.NDialog.warning({
        title: "警告",
        content: "确认删除这条问题反馈？",
        closable: false,
        positiveText: "确认",
        negativeText: "取消",
        onPositiveClick: async () => {
            try {
                await deleteProblem(row.id);
                window.NMessage.success("删除成功");
                handleReset();
            } catch (err) {
                window.NMessage.error((err as Error).message);
            }
        },
    });
};

const handleChangeStatus = async () => {
    const status = currentStatus.value;
    const page = pagination[status].page;
    if (problems[status].has(page))
        currentProblems.value = problems[status].get(page)!;
    else {
        await handleGetProblems();
    }
};

const handleChangePage = async (page: number) => {
    const status = currentStatus.value;
    if (problems[status].has(page)) {
        currentProblems.value = problems[status].get(page)!;
    } else {
        await handleGetProblems();
    }
};
</script>

<style scoped></style>
